const fs = require('fs');
const path = require('path');
const sharp = require('sharp');

// 需要压缩的图片列表
const TARGET_IMAGES = [
  'miniprogram/images/news/2.jpg',
  'miniprogram/images/news/spring-food.jpg',
  'miniprogram/images/news/3.jpg'
];

// 目标大小（KB）
const TARGET_SIZE = 190; // 略小于200KB的限制

// 创建输出目录
const OUTPUT_DIR = 'compressed_images';
if (!fs.existsSync(OUTPUT_DIR)) {
  fs.mkdirSync(OUTPUT_DIR);
}

/**
 * 获取文件大小（KB）
 */
function getFileSizeInKB(filePath) {
  if (fs.existsSync(filePath)) {
    const stats = fs.statSync(filePath);
    return stats.size / 1024;
  }
  return 0;
}

/**
 * 压缩单个图片
 */
async function compressImage(imagePath) {
  try {
    // 检查文件是否存在
    if (!fs.existsSync(imagePath)) {
      console.log(`文件不存在: ${imagePath}`);
      return {
        path: imagePath,
        status: 'not_found'
      };
    }

    const fileName = path.basename(imagePath);
    const outputPath = path.join(OUTPUT_DIR, fileName);
    const originalSize = getFileSizeInKB(imagePath);
    
    console.log(`处理图片: ${imagePath} (${originalSize.toFixed(2)}KB)`);
    
    // 获取图片格式
    const ext = path.extname(imagePath).toLowerCase();
    
    // 使用sharp处理图片
    let image = sharp(imagePath);
    
    // 初始质量
    let quality = 80;
    let buffer;
    
    // jpg和jpeg使用jpeg配置
    if (ext === '.jpg' || ext === '.jpeg') {
      buffer = await image
        .jpeg({ quality })
        .toBuffer();
    } 
    // png使用png配置
    else if (ext === '.png') {
      buffer = await image
        .png({ quality })
        .toBuffer();
    }
    // avif使用avif配置
    else if (ext === '.avif') {
      buffer = await image
        .avif({ quality })
        .toBuffer();
    }
    // 其他格式转换为webp (更小)
    else {
      buffer = await image
        .webp({ quality })
        .toBuffer();
    }
    
    // 检查压缩后大小
    const compressedSize = buffer.length / 1024;
    
    // 如果还是太大，尝试调整尺寸
    if (compressedSize > TARGET_SIZE) {
      // 获取原始尺寸
      const metadata = await image.metadata();
      
      // 按比例缩小尺寸，目标是达到200KB以下
      const ratio = Math.sqrt(TARGET_SIZE / compressedSize) * 0.95; // 稍微多压缩一点
      const newWidth = Math.floor(metadata.width * ratio);
      
      if (ext === '.jpg' || ext === '.jpeg') {
        buffer = await image
          .resize(newWidth)
          .jpeg({ quality: 80 })
          .toBuffer();
      } else if (ext === '.png') {
        buffer = await image
          .resize(newWidth)
          .png({ quality: 80 })
          .toBuffer();
      } else {
        // 其他格式转为 webp
        buffer = await image
          .resize(newWidth)
          .webp({ quality: 80 })
          .toBuffer();
      }
    }
    
    // 最终大小
    const finalSize = buffer.length / 1024;
    
    // 保存压缩后的图片
    fs.writeFileSync(outputPath, buffer);
    
    console.log(`压缩完成: ${originalSize.toFixed(2)}KB -> ${finalSize.toFixed(2)}KB (${(100 - finalSize/originalSize*100).toFixed(2)}% 减少)`);
    
    return {
      path: imagePath,
      originalSize,
      newSize: finalSize,
      status: 'compressed'
    };
  } catch (error) {
    console.error(`压缩失败: ${imagePath}`, error);
    return {
      path: imagePath,
      error: error.message,
      status: 'error'
    };
  }
}

/**
 * 主函数
 */
async function main() {
  console.log('开始压缩指定图片...');
  
  // 检查图片是否存在
  const existingImages = TARGET_IMAGES.filter(img => fs.existsSync(img));
  
  if (existingImages.length === 0) {
    console.log('没有找到任何指定的图片！');
    return;
  }
  
  console.log(`找到 ${existingImages.length} 张图片，准备压缩...`);
  
  // 压缩所有图片
  const results = [];
  
  for (const img of existingImages) {
    const result = await compressImage(img);
    results.push(result);
  }
  
  // 汇总报告
  const successCount = results.filter(r => r.status === 'compressed').length;
  const errorCount = results.filter(r => r.status === 'error').length;
  const notFoundCount = results.filter(r => r.status === 'not_found').length;
  
  console.log('\n压缩完成！汇总报告:');
  console.log(`- 总图片数: ${results.length}`);
  console.log(`- 成功压缩: ${successCount}`);
  console.log(`- 压缩失败: ${errorCount}`);
  console.log(`- 文件不存在: ${notFoundCount}`);
  
  if (successCount > 0) {
    const originalTotalSize = results.reduce((sum, r) => sum + (r.originalSize || 0), 0);
    const newTotalSize = results.reduce((sum, r) => sum + (r.newSize || 0), 0);
    
    console.log(`\n总大小: ${originalTotalSize.toFixed(2)}KB -> ${newTotalSize.toFixed(2)}KB`);
    console.log(`节省了: ${(originalTotalSize - newTotalSize).toFixed(2)}KB (${((1 - newTotalSize/originalTotalSize) * 100).toFixed(2)}%)`);
  }
  
  console.log(`\n压缩后的图片保存在 "${OUTPUT_DIR}" 目录中`);
  console.log('请将压缩后的图片替换原图片，或者将图片保存在云存储中通过URL引用。');
}

main().catch(console.error); 